package com.judysen.jsqlweb.utils;

import com.judysen.jsqlweb.exceptions.ServiceException;
import com.judysen.jsqlweb.models.RestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 统一异常处理
 */
@ControllerAdvice(basePackages = "com.judysen.jsqlweb.controller")
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 具体的异常逻辑处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RestResult handle(Exception e) {
        var restResult = new RestResult();
        if (e instanceof ServiceException) {
            var serviceException = (ServiceException) e;
            restResult.setCode(serviceException.getCode());
            restResult.setMsg(serviceException.getMessage());
        } else {
            restResult.setCode(500);
            restResult.setMsg("系统异常，请联系管理员！");
        }
        logger.error(e.getMessage(), e);                            //打印异常日志
        return restResult;
    }
}
